<?php

namespace App\Controllers\Experience;

use App\Models\Goods\Goods;
use App\Models\Experience\ExpGoods;
use App\Libs\Helper\CommonHelper;
use App\Models\Experience\ExpOrder;
use App\Libs\Base\Constant;

class GetMyApply extends \App\Libs\Base\BaseAction
{
    protected function beforeRun()
    {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }


    public function execute()
    {
        $uid = $this->session->user->id;
        $page = $this->request->get('page', 'int', 1);
        $num = $this->request->get('num', 'int', 5);
        $offset = ($page - 1) * $num;
        $myOrderInfo = ExpOrder::findAll([
            'conditions' => 'uid = ?1',
            'columns' => 'id,eid,status as status_val,ctime as applytime',
            'offset' => $offset,
            'limit' => $num,
            'bind' => [1 => $uid]
        ])->toArray();

        //出错判断：
        if (empty($myOrderInfo)) {
            return \App\Libs\Views\Json::view(0, '没有申请任何体验商品', null);
        }
        foreach ($myOrderInfo as $val) {
            $eidArray[] = $val['eid'];
        }
        $expInfo = ExpGoods::findAll([
            'conditions' => 'id IN ({eid:array})',
            'columns' => 'id as eid,gid,label_url',
            'bind' => ['eid' => $eidArray]
        ])->toArray();

        //得到商品id
        foreach ($expInfo as $key => $val) {
            $gidArray[] = $val['gid'];
        }
        //去获得商品信息
        $goodsInfo = Goods::getGoodsInfo($gidArray, 'id,goods_name,goods_img');

        foreach ($expInfo as $key => $val) {
            if (isset($goodsInfo[$expInfo[$key]['gid']])) {
                unset($goodsInfo[$expInfo[$key]['gid']]['id']);
                $expInfo[$key] = array_merge($expInfo[$key], $goodsInfo[$expInfo[$key]['gid']]);
            }
        }
        $transExpInfo = CommonHelper::setColToKey($expInfo, 'eid');
        foreach ($myOrderInfo as $key => $val) {
            if (isset($transExpInfo[$myOrderInfo[$key]['eid']])) {
                $myOrderInfo[$key] = array_merge($myOrderInfo[$key], $transExpInfo[$myOrderInfo[$key]['eid']]);
            }
        }
        //将数字转换为文字
        foreach ($myOrderInfo as $key => $val) {
            /*
             * 1:正在审核...
             * 2：审核成功
             * 3:未通过......
             */
            switch ($val['status_val']) {
                case 1 :
                    $myOrderInfo[$key]['status_text'] = '正在审核...';
                    break;
                case 2 :
                    $myOrderInfo[$key]['status_text'] = '审核成功';
                    break;
                case 3 :
                    $myOrderInfo[$key]['status_text'] = '未通过......';
                    break;
				case 4 :
                    $myOrderInfo[$key]['status_text'] = '已使用';
                    break;
            }
        }

        return \App\Libs\Views\Json::view(0, '成功', $myOrderInfo);
    }
}
